package com.wondream.myframework.app.common.aspect;

import com.wondream.myframework.app.common.annotation.DecryptAnno;
import com.wondream.myframework.app.common.config.datasource.DynamicDataSourceHolder2;
import com.wondream.myframework.app.common.constant.Constants;
import com.wondream.myframework.app.common.exception.BusinessExeceptionCode;
import com.wondream.myframework.app.common.util.FieldUtils;
import com.wondream.myframework.app.common.util.SpringUtils;
import com.wondream.myframework.app.vo.base.OpRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 订单号解密处理
 */
@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class DataSourceSelectAspect {

    @Around("execution(public * com.wondream.myframework.app.service.*.*(..))")
    public Object executeCommon(ProceedingJoinPoint pjp) throws Throwable {
        return execute(pjp, Constants.DBSource.MALL);
    }

    @Around("execution(public * com.wondream.myframework.app.service.cfsscofl..*.*(..))")
    public Object executeCfss(ProceedingJoinPoint pjp) throws Throwable {
        return execute(pjp, Constants.DBSource.CFSSCOFL);
    }



    /**
     * 拦截要执行的目标方法
     */
    public Object execute(ProceedingJoinPoint pjp, String dataSource) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Object result = null;
        String preDB = null;
        try {
            preDB = DynamicDataSourceHolder2.getCurrent();
            DynamicDataSourceHolder2.put(dataSource);
            result = pjp.proceed();
        } catch (Exception e) {
            log.error("切换数据源失败");
            throw e;
        } finally {
            if(StringUtils.isNotBlank(preDB)){
                DynamicDataSourceHolder2.put(preDB);
            } else {
                DynamicDataSourceHolder2.remove();
            }
        }
        return result;
    }
}
